package band.wukong.practice.rabbitmq.official.torturial.workqueues;

import band.wukong.practice.rabbitmq.official.torturial.helloworld.HiQConst;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author wukong(wukonggg@139.com)
 */
public class WorkQueuesPublisher {

    private static final Logger logger = LoggerFactory.getLogger(WorkQueuesPublisher.class);

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HiQConst.HOST_NAME);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(HiQConst.QUEUE_NAME, false, false, false, null);
        String message = getMessage(args);
        channel.basicPublish("", HiQConst.QUEUE_NAME, null, message.getBytes());
        logger.debug(" [x] Sent '" + message + "'");

        channel.close();
        connection.close();
    }

    private static String getMessage(String[] args){
        if (args.length < 1)
            return "Hello World!";
        return joinStrings(args, " ");
    }

    private static String joinStrings(String[] args, String delimiter) {
        int length = args.length;
        if (length == 0) return "";
        StringBuilder words = new StringBuilder(args[0]);
        for (int i = 1; i < length; i++) {
            words.append(delimiter).append(args[i]);
        }
        return words.toString();
    }
}
